package com.dongrj.framework.starter.log.send;


import com.dongrj.framework.core.thread.NameThreadFactory;
import com.dongrj.framework.core.utils.StringUtils;
import com.dongrj.framework.starter.log.model.ELKModel;
import com.dongrj.framework.starter.log.thread.ELKRejectedExecutionHandler;
import com.dongrj.framework.starter.log.thread.ELKTask;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author dongrongjun
 * @date 2020/06/18
 */
public class DefaultElkSend implements ElkSend {

    private static volatile DefaultElkSend instance;

    public static final Integer MAX_LEN = 800;

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(2500), new NameThreadFactory("ElkPool"), new ELKRejectedExecutionHandler());

    public static DefaultElkSend getInstance() {
        if (instance == null) {
            synchronized (DefaultElkSend.class) {
                if (instance == null) {
                    instance = new DefaultElkSend();
                }
            }
        }
        return instance;
    }

    @Override
    public void send(ELKModel elkModel) {
        String exception = elkModel.getException();
        if (StringUtils.isNotEmpty(exception) && exception.length() > MAX_LEN) {
            String substring = exception.substring(0, MAX_LEN - 1);
            elkModel.setException(substring);
        }
        executor.execute(new ELKTask(elkModel));
    }
}
